package com.my.ecommercesystem.controller;

import com.github.pagehelper.Page;
import com.my.ecommercesystem.dto.CartDto;
import com.my.ecommercesystem.dto.GoodsDto;
import com.my.ecommercesystem.dto.MyMessage;
import com.my.ecommercesystem.entity.Goods;
import com.my.ecommercesystem.entity.Order_Item;
import com.my.ecommercesystem.entity.User;
import com.my.ecommercesystem.service.GoodsService;
import com.my.ecommercesystem.service.ShopCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@RestController
public class ShopCartController {
    @Resource
    private ShopCartService shopCartService;

    @Resource
    private GoodsService goodsService;

    @Autowired
    private RedisTemplate redisTemplate;
    /*@RequestMapping("/test2")
    public String cart(){
        Type type = new Type(1,"阿萨德");
        return JSON.toJSONString(type);
    }*/

    @GetMapping("/queryShopCartByUserId")
    @ResponseBody
    public MyMessage queryShopCartByUserId(Integer size, Integer page, Integer id, HttpSession session, HttpServletRequest request, CartDto shopCartDto) throws Exception {

        Integer mypage = 1;
        Integer mysize = 3;
        MyMessage myMessage = new MyMessage();

        try {
            mypage = Integer.valueOf(page);
        } catch (Exception e) {

        }
        try {
            mysize = Integer.valueOf(size);
        } catch (Exception e) {

        }
        User user= (User) session.getAttribute("loginuser");
        Integer count = shopCartService.queryShopCartCount(1);
        //session.setAttribute("cartcount",count);
        myMessage.setCount(count);
        Integer allcount = shopCartService.sumCartallcount(user.getUser_id());
        //session.setAttribute("allcount",allcount);
        myMessage.setAllcount(allcount);
        double sumtotal = shopCartService.sumCartsubtotal(user.getUser_id());
        //session.setAttribute("alltotal",cartDto);
        myMessage.setSumtotal(sumtotal);
        int maxpage = (count % mysize == 0 ? (count / mysize) : (count / mysize + 1));

        //上限下限已经由pagehelper修正，不好用，我们自己修正
        mypage = mypage < 1 ? 1 : mypage;
        mypage = mypage > maxpage ? maxpage : mypage;


        Page<CartDto> list = shopCartService.queryAllShopCart(user.getUser_id(), page, size);
        //Integer uid=Integer.valueOf(id);
        myMessage.setData(list);
        myMessage.setPage(page);
        myMessage.setMaxPage(maxpage);
        myMessage.setSize(size);
        myMessage.setCode("200");
        myMessage.setFlag(1);
        myMessage.setInfo("查询成功");
//        request.setAttribute("shopCartDto",shopCartDto);
        return myMessage;

    }

    @RequestMapping("/addShopCart")
    public MyMessage addShopCart(CartDto shopCartDto, HttpServletResponse response, HttpSession session) throws Exception {
        MyMessage myMessage = new MyMessage();
        User user = (User) session.getAttribute("loginuser");

        //调用insertShopCart方法插入数
        if (user == null) {
            myMessage.setFlag(0);
        } else {
            Integer uid = user.getUser_id();
            //Integer uid = 1;
            Goods goods = (Goods) session.getAttribute("goodsdtl");
            shopCartDto.setGoods_id(goods.getGoods_id());
            Integer gid = shopCartDto.getGoods_id();

            // 是：表示该用户的购物车没有该商品，则需要执行insert操作
            // -- 调用queryGoodsByGoodsId方法得到商品详情，该数据中包含商品价格
            Goods goods2 = goodsService.queryGoodsByGoodsId(gid);
            //补全shopCart对象的属性

            shopCartDto.setUser_id(uid);
            shopCartDto.setGoods_id(gid);
            //小计类型转换
            double goods_subtotal = shopCartDto.getGoods_subtotal();
            shopCartDto.setGoods_subtotal(goods_subtotal);
            //数量类型转换
            Integer goods_number = shopCartDto.getGoods_number();
            shopCartDto.setGoods_number(goods_number);
            Order_Item order_item=new Order_Item();
            order_item.setOrder_item_name(goods.getGoods_name());
            String code=user.getUser_phone()+System.currentTimeMillis();
            order_item.setOrder_item_code(code);
            order_item.setOrder_item_goodsid(goods.getGoods_id());
            order_item.setOrder_item_number(goods_number);
            order_item.setOrder_item_singletotalprice(goods_subtotal);
            order_item.setOrder_item_price(goods.getGoods_price());

            CartDto result = shopCartService.queryCarByUseridAndGoodsid(uid, gid);
            //判断查询结果是否为空
            if (result == null) {
                if (shopCartService.addOrder_Item(order_item,shopCartDto)) {
                    myMessage.setFlag(1);
                } else {
                    myMessage.setFlag(3);
                    System.out.println("添加失败");
                }
            } else {
                // 否：表示该用户的购物车已有该商品，则需要执行update操作增加数量
                // 从查询结果中获取cid
                Integer cid = result.getCart_id();
                // 从查询结果中取出原有数量，与参数num相加，得到新的数量
                Integer allnum = result.getGoods_number() + goods_number;
                //从查询结果中取出原有小计，与参数subtotal相乘，得到新的小计

                double allsubtotal = result.getGoods_subtotal() + goods_subtotal;
                //调用updateCartNumAndSubtotalByCartId方法执行修改数量
                shopCartService.updateCartNumAndSubtotalByCartId(cid, allnum, allsubtotal);
                myMessage.setFlag(1);
            }


        }
        return myMessage;
    }

    @RequestMapping("/deleteShorCartByCartId")
    public void deleteShorCartByCartId(Integer cart_id, HttpServletResponse response) throws IOException {
        PrintWriter out = response.getWriter();
        if (cart_id == null || cart_id < 0) {
            out.print("<script>alert('取消失败，参数错误！');history.go(-1)</script>");
            System.out.println(cart_id);
        } else {
            if (shopCartService.deleteShorCartByCartId(cart_id)) {
                out.print("<script>location.href='shopcar'</script>");
            } else {
                out.print("<script>alert('取消失败,请重新再试...');history.go(-1)'</script>");
            }
        }
        out.flush();
        out.close();
    }
}
